package com.freesun.shop.config;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.freesun.shop.service.SysUserService;
import com.freesun.shop.entity.SysUser;
import com.freesun.shop.vo.Auth;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

@Configuration
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser user = (SysUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String authJson = redisTemplate.opsForValue().get(Auth.USER_AUTH_PREFIX + user.getUserId());
        JSONArray jsonArray= JSONUtil.parseArray(authJson);
        List<String> permission = JSONUtil.toList(jsonArray, String.class);
        info.addStringPermissions(permission);

        return info;
    }

    /**
     * 登录
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取登录用户名
        String username = token.getPrincipal().toString();
      SysUser user = sysUserService.findUserByName(username);
        //通过用户名查询用户
        //查询该用户的权限信息
        //返回授权的对象
        ByteSource credentialsSalt=ByteSource.Util.bytes("whsxt".getBytes());
        return new SimpleAuthenticationInfo(user,user.getPassword(),credentialsSalt,username);
    }

    public static void main(String[] args) {
        Md5Hash hash = new Md5Hash("123456", ByteSource.Util.bytes("whsxt".getBytes()), 2);
        String hex = hash.toHex();
        System.out.println("hex = " + hex);
    }
}
